<template>
  <div>
    <van-nav-bar title="我的" left-arrow @click-left="GOback" placeholder :border="false" />
    <van-form @submit="onSubmit">
      <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名" :rules="[{ required: true, message: '请填写用户名' }]" />
      <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码" :rules="[{ required: true, message: '请填写密码' }]" autocomplete="off" />

      <van-field v-model="captcha_code" center label="验证码" placeholder="验证码" :rules="[{ required: true, message: '请输入验证码' }]">
      </van-field>
      <img @click="cation" :src="this.requ" alt="">
      <span class="requie">注:未注册账号,登录时将自动注册</span>
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
    <!-- 验证失效和 密码错误-->
    <van-dialog v-model="show1" confirmButtonColor="#3199e8">
      <template #default>
        <div class="tip_icon">
          <span></span>
          <span></span>
        </div>
        <p class="tip_text">{{message==='密码错误'?message:message}}</p>
      </template>
    </van-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //用户名
      username: '',
      //密码
      password: '',
      //验证码
      captcha_code: '',
      //验证码base64地址
      requ: '',
      show1: false,
      message: ''
    }
  },
  methods: {
    GOback() {
      this.$router.go(-1)
    },
    //登录
    async onSubmit() {
      //this.$store.dispatch('Userinfo', this.userdeng)

      const { data: res } = await this.reques.post('v2/login', {
        username: this.username,
        password: this.password,
        captcha_code: this.captcha_code
      })
      // 将用户ID存入sessionStorage
      console.log(res)
      window.sessionStorage.setItem('user_id', res.user_id)

      if (res.message === '验证码失效') {
        this.captcha_code = ''
      }
      if (res.message === '密码错误' || res.message === '验证码失效' || res.message === '登陆失败' || res.message === '验证码不正确') {
        this.show1 = true
        this.message = res.message
        this.cation()
      } else {
        const geohash = window.sessionStorage.getItem('geohash')
        if (geohash) {
          this.$router.replace('/user')
        } else {
          this.$router.replace('/msite')
        }
      }
    },
    //验证码
    async cation() {
      // this.$store.dispatch('cationinfo')
      const { data: res } = await this.reques.post('v1/captchas')
      this.requ = res.code
    }
  },
  mounted() {
    this.cation()
  }
}
</script>

<style lang="less" scoped>
.requie {
  margin-left: 0.5rem;
  margin-top: 0.7rem;
  display: block;
  color: red;
}
img {
  top: 6rem;
  right: 1rem;
  position: absolute;
}
</style>